require "dgo/tile_map/palet_chip"
require "gadgets/frame"
require "map_loader"
require "find"

module MapEditor
  class AutoPaletPanel < PaletPanel
    include DGO::TileMap
    def initialize(model, controlers, default_controler)
      super(model, controlers, default_controler)
      @palet_chips = []
    end
    
    def x_count
      if @palet_chips.length < $config.palet_x_count
        return @palet_chips.length
      else
        return $config.palet_x_count
      end
    end
    
    def y_count
      return (@palet_chips.length / $config.palet_x_count.to_f).ceil
    end
    
    def palet_chips
      return @palet_chips
    end

    def sample_texture
      if @sample_texture.nil?
        @sample_texture = Texture.new(self.x_count * self.grid_width, self.y_count * self.grid_height)
        
        @palet_chips.each_with_index do |palet_chip, i|
          next if palet_chip.chipset.nil?
          tx = (i % self.x_count)
          ty = (i / self.x_count)
          palet_chip.render(@sample_texture, tx, ty, 0, 0, 0, 0, 0, 0)
        end
      end
      return @sample_texture
    end

    def render_samples(s)
      s.render_texture(self.sample_texture, 0, 0, :src_x => self.scroll_x / @zoom, :src_y => self.scroll_y / @zoom)
    end
    
    def load_chipsets(chipsets)
      @palet_chips = []
      @palet_chips << PaletChip.generate_empty_paletchip(true)
      chipsets.each do |chipset|
        chipset.palet_chips.each do |palet_chip|
          @palet_chips << palet_chip
        end
      end
      @scroll_box.set_client_size(self.x_count * self.zoomed_grid_width, self.y_count * self.zoomed_grid_height)
    end  
  end
end

